/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.accident.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.koron.accident.domain.InjuriesRegister;
import com.koron.accident.mapper.InjuriesRegisterMapper;
import com.koron.accident.service.api.InjuriesRegisterService;
import com.koron.accident.util.BusinessCode;
import com.koron.common.bean.StaffBean;
import com.koron.common.dfs.FastDFSClientWrapper;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.util.DocConverterUtils;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class InjuriesRegisterServiceImpl implements InjuriesRegisterService {
    private final static  Logger logger = LoggerFactory.getLogger(InjuriesRegisterServiceImpl.class);

    @Autowired
    private FastDFSClientWrapper clientWrapper;

    @Autowired
    private DocConverterUtils docConverterUtils;

    @Override
    public MessageBean<Integer> save(InjuriesRegister bean, String keepFiles, String delFiles, String pdfKeepFiles, String pdfDelFiles, MultipartFile[] files) {
        MessageBean<Integer> msg = new MessageBean<>();
        List<String> keepList = new ArrayList<>();
        List<String> pdfKeepList = new ArrayList<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(bean.getStaffCode()) || StringUtils.isEmpty(bean.getStaffName())) {
                msg.setCode(BusinessCode.INJURIESREGISTER_EMPTY_STAFF.getCode());
                msg.setDescription(BusinessCode.INJURIESREGISTER_EMPTY_STAFF.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getDepartmentCode()) || StringUtils.isEmpty(bean.getDepartmentName())) {
                msg.setCode(BusinessCode.INJURIESREGISTER_EMPTY_DEPARTMENTCODE.getCode());
                msg.setDescription(BusinessCode.INJURIESREGISTER_EMPTY_DEPARTMENTCODE.getDescription());
                return msg;
            }
            if (StringUtils.isEmpty(bean.getAccidentBulletinId()) || StringUtils.isEmpty(bean.getAccidentBulletinName())) {
                msg.setCode(BusinessCode.INJURIESREGISTER_EMPTY_ACCIDENT.getCode());
                msg.setDescription(BusinessCode.INJURIESREGISTER_EMPTY_ACCIDENT.getDescription());
                return msg;
            }
            if (null != files && files.length > 0) {
                for (MultipartFile file : files) {
                    String url = clientWrapper.uploadFile(file);
                    keepList.add(url + "#" + file.getOriginalFilename());
                    String pdfUrl = docConverterUtils.converterUpdate(file);
                    pdfKeepList.add(StringUtils.isEmpty(pdfUrl) ? null : pdfUrl);
                }
            }
            Integer value = 0;
            if (StringUtils.isEmpty(bean.getId())) {
                //新增
                bean.setId(DefaultIdGenerator.getInstance().generateLongId());
                bean.setAddTime(bean.getUpdateTime());
                bean.setAddUser(bean.getUpdateUser());
                bean.setAddUserName(bean.getUpdateUserName());
                if (null != keepList && keepList.size() > 0)
                    bean.setAttachment(new Gson().toJson(keepList));
                if (null != pdfKeepList && pdfKeepList.size() > 0)
                    bean.setPreviewAttachment(new Gson().toJson(pdfKeepList));
                value = factory.getMapper(InjuriesRegisterMapper.class).insert(bean);
            } else {
                //修改
                InjuriesRegister entity = queryOne(bean.getId()).getData();
                if (null == entity) {
                    msg.setCode(BusinessCode.INJURIESREGISTER_NOT_EXIST.getCode());
                    msg.setDescription(BusinessCode.INJURIESREGISTER_NOT_EXIST.getDescription());
                    return msg;
                }
                if (StringUtils.isNotEmpty(keepFiles)) {
                    String[] keepArray = keepFiles.split("[,，]");
                    keepList.addAll(Arrays.asList(keepArray).stream().map(String::trim).collect(Collectors.toList()));
                }
                if (StringUtils.isNotEmpty(pdfKeepFiles)) {
                    String[] keepArray = pdfKeepFiles.split("[,，]");
                    pdfKeepList.addAll(Arrays.asList(keepArray).stream().map(String::trim).collect(Collectors.toList()));
                }
                if (null != keepList && keepList.size() > 0)
                    bean.setAttachment(new Gson().toJson(keepList));
                if (null != pdfKeepList && pdfKeepList.size() > 0)
                    bean.setPreviewAttachment(new Gson().toJson(pdfKeepList));
                value = factory.getMapper(InjuriesRegisterMapper.class).update(bean);
                if (value > 0) {
                    if (StringUtils.isNotEmpty(delFiles)) {
                        String[] delArray = delFiles.split("[,，]");
                        for (String url : delArray) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                    if (StringUtils.isNotEmpty(pdfDelFiles)) {
                        String[] delArray = pdfDelFiles.split("[,，]");
                        for (String url : delArray) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            if (value > 0) {
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("工伤登记保存成功");
                msg.setData(value);
                return msg;
            } else {
                if (null != keepList && keepList.size() > 0) {
                    if (StringUtils.isEmpty(keepFiles)) {
                        for (String url : keepList) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    } else {
                        List<String> keeps = Arrays.asList(keepFiles.split("[,，]"));
                        for (String url : keepList) {
                            if (!keeps.contains(url)) {
                                clientWrapper.deleteFile(url.split("#")[0]);
                            }
                        }
                    }
                }
                if (null != pdfKeepList && pdfKeepList.size() > 0) {
                    if (StringUtils.isEmpty(pdfKeepFiles)) {
                        for (String url : pdfKeepList) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    } else {
                        List<String> keeps = Arrays.asList(pdfKeepFiles.split("[,，]"));
                        for (String url : pdfKeepList) {
                            if (!keeps.contains(url)) {
                                clientWrapper.deleteFile(url.split("#")[0]);
                            }
                        }
                    }
                }
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("工伤登记保存失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            if (null != keepList && keepList.size() > 0) {
                if (StringUtils.isEmpty(keepFiles)) {
                    for (String url : keepList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(keepFiles.split("[,，]"));
                    for (String url : keepList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            if (null != pdfKeepList && pdfKeepList.size() > 0) {
                if (StringUtils.isEmpty(pdfKeepFiles)) {
                    for (String url : pdfKeepList) {
                        clientWrapper.deleteFile(url.split("#")[0]);
                    }
                } else {
                    List<String> keeps = Arrays.asList(pdfKeepFiles.split("[,，]"));
                    for (String url : pdfKeepList) {
                        if (!keeps.contains(url)) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
            }
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<Integer> delete(String id) {
        MessageBean<Integer> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            InjuriesRegister entity = queryOne(id).getData();
            if (null == entity) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_NOT_EXIST.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_NOT_EXIST.getDescription());
                return msg;
            }
            Integer value = factory.getMapper(InjuriesRegisterMapper.class).delete(id);
            if (value > 0) {
                if (StringUtils.isNotEmpty(entity.getAttachment())) {
                    //删除文件
                    List<String> delFiles = JSONObject.parseArray(entity.getAttachment(), String.class);
                    if (null != delFiles && delFiles.size() > 0) {
                        for (String url : delFiles) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
                if (StringUtils.isNotEmpty(entity.getPreviewAttachment())) {
                    //删除pdf文件
                    List<String> delFiles = JSONObject.parseArray(entity.getPreviewAttachment(), String.class);
                    if (null != delFiles && delFiles.size() > 0) {
                        for (String url : delFiles) {
                            clientWrapper.deleteFile(url.split("#")[0]);
                        }
                    }
                }
                msg.setCode(BusinessCode.SUCCESS.getCode());
                msg.setDescription("工伤登记删除成功");
                msg.setData(value);
                return msg;
            } else {
                msg.setCode(BusinessCode.FAILURE.getCode());
                msg.setDescription("工伤登记删除失败");
                msg.setData(value);
                return msg;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<InjuriesRegister> queryOne(String id) {
        MessageBean<InjuriesRegister> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            if (StringUtils.isEmpty(id)) {
                msg.setCode(BusinessCode.ACCIDENTREPORT_NOT_CHANGE_DATA.getCode());
                msg.setDescription(BusinessCode.ACCIDENTREPORT_NOT_CHANGE_DATA.getDescription());
                return msg;
            }
            InjuriesRegister entity = factory.getMapper(InjuriesRegisterMapper.class).queryOne(id);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("查询工伤登记详情成功");
            msg.setData(entity);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public MessageBean<DataBean<InjuriesRegister>> list(String corpCode, String staffName, String departmentCode, Integer start, Integer rows) {
        MessageBean<DataBean<InjuriesRegister>> msg = new MessageBean<>();
        try (SessionFactory factory = new SessionFactory()) {
            List<InjuriesRegister> list = factory.getMapper(InjuriesRegisterMapper.class).queryByCondition(corpCode, staffName, departmentCode, start, rows);
            Integer totalNumber = factory.getMapper(InjuriesRegisterMapper.class).countByCondition(corpCode, staffName, departmentCode);
            rows = rows == null ? totalNumber : (rows <= 0 ? 1 : rows);
            Integer totalPage = (totalNumber > rows) ? (totalNumber % rows == 0 ? totalNumber / rows : totalNumber / rows + 1) : 1;
            DataBean<InjuriesRegister> dataBean = new DataBean<>();
            dataBean.setList(list);
            dataBean.setPageSize(rows);
            dataBean.setTotalPage(totalPage);
            dataBean.setTotalNumber(totalNumber);
            msg.setCode(BusinessCode.SUCCESS.getCode());
            msg.setDescription("获取工伤登记列表成功");
            msg.setData(dataBean);
            return msg;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            msg.setCode(BusinessCode.EXCEPTION.getCode());
            msg.setDescription(BusinessCode.EXCEPTION.getDescription());
            return msg;
        }
    }

    @Override
    public List<InjuriesRegister> exportList(StaffBean user, String corpCode, String staffName, String departmentCode) {
        try (SessionFactory factory = new SessionFactory()) {
            List<InjuriesRegister> list = factory.getMapper(InjuriesRegisterMapper.class).queryByCondition(corpCode, staffName, departmentCode, null, null);
            if (null != list && list.size() > 0) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                list.forEach(bean->{
                    if (null != bean.getDiagnosticTime()){
                        bean.setDiagnosticTimeStr(sdf.format(bean.getDiagnosticTime()));
                    }
                });
            }
            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(),e);
            return null;
        }

    }
}
